package org.example.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.RuleActionEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import org.example.domain.strategy.repository.IStrategyRuleRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.armory.StrategyArmoryDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.factory.DefaultLogicFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain  extends AbstractLogicChain {
    private Long userScore = 5000L;
    @Resource
    IStrategyRuleRepository strategyRuleRepository;
    @Resource
    IStrategyDispatch strategyDispatch;
    @Override
    public String ruleModel() {
        return "rule_weight";
    }

    @Override
    public Long logic(Long userId, Long strategyId) {
        log.info("正进行黑名单前置规则过滤。。。。userId：{}  strategyId：{}", userId, strategyId);
        //查询是否配有权重
        List<StrategyRuleEntity> ruleEntityList = strategyRuleRepository.queryStrategyRuleEntityForModel(strategyId, null, ruleModel());
        Map<Long, List<Long>> valueMap = StrategyRuleEntity.getRuleWeightValueFromList(ruleEntityList);
        if(!valueMap.isEmpty()) {
            Set<Long> keys = valueMap.keySet().stream().sorted().collect(Collectors.toSet());
            Long group = null;
            for (Long key : keys) {
                if(key > userScore) {
                    break;
                }
                group = key;
            }
            if (null != group) {
                Long awardId = strategyDispatch.getRandomStrategyAwardId(strategyId, String.valueOf(group));
                log.info("黑名单前置规则过滤返回。。。。awardId：{}", awardId);
                return awardId;
            }
        }
        return next().logic(userId, strategyId);
    }
}
